package order

import (
	"booking/common/handler"
	"booking/common/validator"
	"booking/models"
	"github.com/gin-gonic/gin"
	jsoniter "github.com/json-iterator/go"
)

func Complete(c *gin.Context) {
	var params struct {
		OrderNo      string               `json:"order_no" binding:"required"`
		CompleteDate string               `json:"complete_date" binding:"required"`
		Attachments  []models.Attachments `json:"attachments"`
	}

	if err := c.ShouldBindJSON(&params); err != nil {
		handler.Error(validator.Translate(err), c)
		return
	}
	var order models.Order
	models.Db.Model(models.Order{}).
		Where(map[string]any{
			"order_no": params.OrderNo,
		}).
		First(&order)
	if order.Id == 0 {
		handler.Error("订单不存在", c)
		return
	}
	var orderAttachments []models.Attachments
	jsoniter.UnmarshalFromString(order.Attachments, &orderAttachments)
	orderAttachments = append(orderAttachments, params.Attachments...)
	orderAttachmentsJson, _ := jsoniter.MarshalToString(orderAttachments)
	models.Db.Model(models.Order{}).Where(map[string]any{
		"order_no": params.OrderNo,
	}).Updates(map[string]any{
		"status":        models.OrderStatusFinished,
		"complete_date": params.CompleteDate,
		"attachments":   orderAttachmentsJson,
	})

	attachments, _ := jsoniter.MarshalToString(&params.Attachments)
	models.Db.Model(models.OrderCourier{}).Where(map[string]any{
		"order_no": params.OrderNo,
	}).Updates(map[string]any{
		"courier_status": models.CourierStatusDelivered,
		"delivery_time":  params.CompleteDate,
		"attachments":    attachments,
	})

	handler.Success(map[string]any{
		"order_no": order.OrderNo,
	}, c)

}
